<template>
    <div class="excel-split-container">
      <div class="page-header">
        <h2>平安银行Excel分表</h2>
        <p>将Excel文件按照指定条件进行分表处理，适用于平安银行数据格式</p>
      </div>
  
      <div class="content-wrapper">
        <!-- 文件上传区域 -->
        <div class="upload-section">
          <a-card title="文件上传" class="upload-card">
            <div class="upload-area">
              <a-upload-dragger
                v-model:fileList="fileList"
                :beforeUpload="beforeUpload"
                accept=".xlsx,.xls"
                :multiple="false"
                @change="handleUploadChange"
                @remove="handleRemove"
              >
                <p class="ant-upload-drag-icon">
                  <inbox-outlined />
                </p>
                <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
                <p class="ant-upload-hint">
                  支持 .xlsx 和 .xls 格式的Excel文件
                </p>
              </a-upload-dragger>
            </div>
          </a-card>
        </div>
  
        <!-- Excel预览区域 -->
        <div class="preview-section" v-if="fileList.length > 0 && excelData.length > 0">
          <a-card title="Excel预览" class="preview-card">
            <template #extra>
              <a-space>
                <a-button @click="showFullPreview" type="primary" size="small">
                  <eye-outlined />
                  全屏预览
                </a-button>
                <a-button @click="refreshPreview" size="small">
                  <reload-outlined />
                  刷新
                </a-button>
              </a-space>
            </template>
            
            <div class="preview-info">
              <a-descriptions size="small" :column="4">
                <a-descriptions-item label="文件名">
                  {{ currentFile?.name }}
                </a-descriptions-item>
                <a-descriptions-item label="总行数">
                  {{ excelData.length }}
                </a-descriptions-item>
                <a-descriptions-item label="总列数">
                  {{ excelColumns.length }}
                </a-descriptions-item>
                <a-descriptions-item label="文件大小">
                  {{ formatFileSize(currentFile?.size) }}
                </a-descriptions-item>
              </a-descriptions>
            </div>
  
            <div class="preview-table">
              <a-table
                :columns="previewColumns"
                :data-source="excelData"
                :pagination="false"
                :scroll="{ x: 800, y: 400 }"
                size="small"
                bordered
              >
                <template #bodyCell="{ column, index }">
                  <template v-if="column?.key === 'index'">
                    {{ index + 1 }}
                  </template>
                </template>
              </a-table>
            </div>
          </a-card>
        </div>
  
        <!-- 分表配置区域 -->
        <div class="config-section" v-if="fileList.length > 0">
          <a-card title="分表配置" class="config-card">
            <div class="split-info">
              <a-alert
                message="分表说明"
                description="系统将根据上传的Excel数据生成新的Excel文件，使用模板格式输出。请先上传分表模板来指定输出格式。"
                type="info"
                show-icon
                style="margin-bottom: 20px"
              />
              
              <a-descriptions size="small" :column="2" bordered>
                <a-descriptions-item label="处理方式">
                  直接生成新表
                </a-descriptions-item>
                <a-descriptions-item label="数据行数" v-if="excelData.length > 0">
                  <span class="highlight">{{ excelData.length }} 行数据</span>
                </a-descriptions-item>
                <a-descriptions-item label="预计生成文件数">
                  <span class="highlight">1 个文件</span>
                </a-descriptions-item>
              </a-descriptions>
            </div>
  
            <!-- 分表模板上传区域 -->
            <div class="template-upload-section">
              <a-divider orientation="left">
                <span style="font-weight: 600;">分表模板（必填）</span>
                <span style="color: #ff4d4f; margin-left: 4px;">*</span>
              </a-divider>
              
              <div class="template-upload-area">
                <a-upload-dragger
                  v-model:fileList="templateFileList"
                  :beforeUpload="beforeTemplateUpload"
                  accept=".xlsx,.xls"
                  :multiple="false"
                  @change="handleTemplateUploadChange"
                  @remove="handleTemplateRemove"
                  :maxCount="1"
                >
                  <p class="ant-upload-drag-icon">
                    <file-text-outlined />
                  </p>
                  <p class="ant-upload-text">点击或拖拽模板文件到此区域上传</p>
                  <p class="ant-upload-hint">
                    支持 .xlsx 和 .xls 格式的Excel模板文件，必须包含"金融资产"、"客户"、"分案关系"三个工作表
                  </p>
                </a-upload-dragger>
              </div>
  
              <!-- 模板信息显示 -->
              <div v-if="templateFileList.length > 0 && templateInfo" class="template-info">
                <a-alert
                  :message="`模板文件：${templateInfo.fileName}`"
                  :description="`检测到 ${templateInfo.sheetCount} 个工作表`"
                  type="success"
                  show-icon
                  style="margin-top: 16px"
                />
                
                <!-- 工作表列表 -->
                <div v-if="templateInfo.worksheets && templateInfo.worksheets.length > 0" class="template-worksheets">
                  <a-tabs size="small" type="card" style="margin-top: 12px;">
                    <a-tab-pane 
                      v-for="(worksheet, index) in templateInfo.worksheets" 
                      :key="index"
                      :tab="`${worksheet.name} (${worksheet.dataCount}行)`"
                    >
                      <div class="worksheet-preview">
                        <div class="worksheet-info">
                          <div class="info-item">
                            <span class="info-label">表头行：</span>
                            <span class="info-value">第{{ worksheet.headerRow }}行</span>
                          </div>
                          <div class="info-item">
                            <span class="info-label">数据起始行：</span>
                            <span class="info-value">第{{ worksheet.dataStartRow }}行</span>
                          </div>
                          <div class="info-item">
                            <span class="info-label">数据行数：</span>
                            <span class="info-value">{{ worksheet.dataCount }}行</span>
                          </div>
                          <div class="info-item">
                            <span class="info-label">列数：</span>
                            <span class="info-value">{{ worksheet.headers.length }}列</span>
                          </div>
                        </div>
                      </div>
                    </a-tab-pane>
                  </a-tabs>
                </div>
                
                <div class="template-actions" style="margin-top: 12px;">
                  <a-space>
                    <a-button 
                      type="link" 
                      size="small" 
                      @click="previewTemplate"
                      :loading="templatePreviewLoading"
                    >
                      <eye-outlined />
                      预览模板
                    </a-button>
                    <a-button 
                      type="link" 
                      size="small" 
                      @click="clearTemplate"
                      danger
                    >
                      <delete-outlined />
                      清除模板
                    </a-button>
                  </a-space>
                </div>
              </div>
            </div>
  
            <!-- 银行名称输入 -->
            <div class="bank-name-section">
              <a-divider orientation="left">
                <span style="font-weight: 600;">银行信息</span>
              </a-divider>
              
              <a-form
                :model="splitConfig"
                :label-col="{ span: 6 }"
                :wrapper-col="{ span: 18 }"
                @finish="handleSplit"
                style="margin-top: 20px"
              >
                <a-form-item 
                  label="银行名称" 
                  name="bankName"
                >
                  <a-input 
                    v-model:value="splitConfig.bankName" 
                    placeholder="请输入银行名称，如：中信银行、平安银行等"
                    style="width: 100%"
                  />
                </a-form-item>
  
                <a-form-item :wrapper-col="{ offset: 6, span: 18 }">
                <a-space>
                  <a-button
                    type="primary"
                    html-type="submit"
                    :loading="splitting"
                    :disabled="!canSplit"
                  >
                    生成新表
                  </a-button>
                </a-space>
                <div v-if="!templateInfo" style="margin-top: 8px; color: #ff4d4f; font-size: 12px;">
                  请先上传分表模板文件
                </div>
                </a-form-item>
              </a-form>
            </div>
          </a-card>
        </div>
  
        <!-- 分表结果区域 -->
        <div class="result-section" v-if="splitResults.length > 0">
          <a-card title="分表结果" class="result-card">
            <template #extra>
              <a-space>
                <a-button 
                  type="primary" 
                  size="small" 
                  @click="downloadAllFiles"
                  :loading="downloadingAll"
                >
                  <download-outlined />
                  批量下载
                </a-button>
                <a-button 
                  size="small" 
                  @click="refreshResults"
                >
                  <reload-outlined />
                  刷新
                </a-button>
              </a-space>
            </template>
            
            <a-table
              :columns="resultColumns"
              :data-source="splitResults"
              :pagination="false"
              size="small"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'action'">
                  <a-space>
                    <a-button
                      type="link"
                      size="small"
                      @click="downloadFile(record)"
                    >
                      下载
                    </a-button>
                    <a-button
                      type="link"
                      size="small"
                      @click="previewFile(record)"
                    >
                      预览
                    </a-button>
                  </a-space>
                </template>
              </template>
            </a-table>
          </a-card>
        </div>
      </div>
  
      <!-- 全屏预览Modal -->
      <a-modal
        v-model:open="fullPreviewVisible"
        title="Excel全屏预览"
        :width="'90vw'"
        :style="{ top: '20px' }"
        :footer="null"
        :destroyOnClose="true"
      >
        <div class="full-preview-container">
          <div class="full-preview-header">
            <a-descriptions size="small" :column="4">
              <a-descriptions-item label="文件名">
                {{ currentFile?.name }}
              </a-descriptions-item>
              <a-descriptions-item label="总行数">
                {{ excelData.length }}
              </a-descriptions-item>
              <a-descriptions-item label="总列数">
                {{ excelColumns.length }}
              </a-descriptions-item>
              <a-descriptions-item label="文件大小">
                {{ formatFileSize(currentFile?.size) }}
              </a-descriptions-item>
            </a-descriptions>
          </div>
          
          <!-- 按机构分组的选项卡 -->
          <div class="institution-tabs-container">
            <a-tabs type="card" v-model:activeKey="activeInstitutionTab">
              <a-tab-pane 
                v-for="institutionName in institutionNames" 
                :key="institutionName"
                :tab="`${institutionName} (${groupedPreviewData[institutionName]?.length || 0}条)`"
              >
                <div class="institution-preview-table">
                  <a-table
                    :columns="fullPreviewColumns"
                    :data-source="groupedPreviewData[institutionName] || []"
                    :pagination="false"
                    :scroll="{ x: 'max-content', y: '60vh' }"
                    size="small"
                    bordered
                    :row-key="(record: any) => record.key || Math.random().toString(36).substr(2, 9)"
                  >
                    <template #bodyCell="{ column, index }">
                      <template v-if="column?.key === 'index'">
                        {{ index + 1 }}
                      </template>
                    </template>
                  </a-table>
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
        </div>
      </a-modal>
  
      <!-- 机构数据预览Modal -->
      <a-modal
        v-model:open="previewModalVisible"
        :title="`${previewInstitutionName} - ${getPreviewTableTitle()}预览`"
        :width="'90vw'"
        :style="{ top: '20px' }"
        :footer="null"
        :destroyOnClose="true"
      >
        <div class="institution-preview-container">
          <div class="institution-preview-header">
            <a-descriptions size="small" :column="4">
              <a-descriptions-item label="机构名称">
                {{ previewInstitutionName }}
              </a-descriptions-item>
              <a-descriptions-item label="数据行数">
                {{ previewInstitutionData.length }}
              </a-descriptions-item>
              <a-descriptions-item label="总列数">
                {{ excelColumns.length }}
              </a-descriptions-item>
              <a-descriptions-item label="预览时间">
                {{ new Date().toLocaleString() }}
              </a-descriptions-item>
            </a-descriptions>
          </div>
          
          <div class="institution-preview-table">
            <a-table
              :columns="previewColumns"
              :data-source="previewInstitutionData"
              :pagination="false"
              :scroll="{ x: 'max-content', y: '60vh' }"
              size="small"
              bordered
              :row-key="(record: any) => record.key || Math.random().toString(36).substr(2, 9)"
            >
              <template #bodyCell="{ column, index }">
                <template v-if="column?.key === 'index'">
                  {{ index + 1 }}
                </template>
              </template>
            </a-table>
          </div>
        </div>
      </a-modal>
  
      <!-- 模板预览Modal -->
      <a-modal
        v-model:open="templatePreviewVisible"
        title="分表模板预览"
        :width="'90vw'"
        :style="{ top: '20px' }"
        :footer="null"
        :destroyOnClose="true"
      >
        <div class="template-preview-container">
          <div class="template-preview-header">
            <a-descriptions size="small" :column="4">
              <a-descriptions-item label="模板文件名">
                {{ templateInfo?.fileName }}
              </a-descriptions-item>
              <a-descriptions-item label="工作表数量">
                {{ templateInfo?.sheetCount }}
              </a-descriptions-item>
              <a-descriptions-item label="总列数">
                {{ templateInfo?.worksheets?.reduce((sum, ws) => sum + ws.headers.length, 0) || 0 }}
              </a-descriptions-item>
              <a-descriptions-item label="总行数">
                {{ templateInfo?.worksheets?.reduce((sum, ws) => sum + ws.dataCount, 0) || 0 }}
              </a-descriptions-item>
            </a-descriptions>
          </div>
          
          <!-- 工作表标签页 -->
          <div v-if="templateInfo?.worksheets && templateInfo.worksheets.length > 0" class="template-worksheets-tabs">
            <a-tabs type="card" @change="handleTemplateTabChange">
              <a-tab-pane 
                v-for="(worksheet, index) in templateInfo.worksheets" 
                :key="index"
                :tab="`${worksheet.name} (${worksheet.dataCount}行)`"
              >
                <div class="worksheet-preview-content">
                  <div class="worksheet-info">
                    <div class="info-item">
                      <span class="info-label">表头行：</span>
                      <span class="info-value">第{{ worksheet.headerRow }}行</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">数据起始行：</span>
                      <span class="info-value">第{{ worksheet.dataStartRow }}行</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">数据行数：</span>
                      <span class="info-value">{{ worksheet.dataCount }}行</span>
                    </div>
                    <div class="info-item">
                      <span class="info-label">列数：</span>
                      <span class="info-value">{{ worksheet.headers.length }}列</span>
                    </div>
                  </div>
                  
                  <div class="worksheet-preview-table">
                    <a-table
                      :columns="worksheet.columns"
                      :data-source="worksheet.data"
                      :pagination="false"
                      :scroll="{ x: 'max-content', y: '50vh' }"
                      size="small"
                      bordered
                      :row-key="(record: any) => record.key || Math.random().toString(36).substr(2, 9)"
                    >
              <template #bodyCell="{ column, index }">
                <template v-if="column?.key === 'index'">
                  {{ index + 1 }}
                </template>
              </template>
            </a-table>
                  </div>
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
        </div>
      </a-modal>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, reactive } from 'vue';
  import { message } from 'ant-design-vue';
  import { InboxOutlined, EyeOutlined, ReloadOutlined, DownloadOutlined, FileTextOutlined, DeleteOutlined } from '@ant-design/icons-vue';
  import type { UploadFile, TableColumnsType } from 'ant-design-vue';
  import * as ExcelJS from 'exceljs';
  import dayjs from 'dayjs';
  
  // 接口定义
  interface SplitConfig {
    bankName?: string; // 银行名称
  }
  
  interface SplitResult {
    key: string;
    institutionName: string;
    fileName: string;
    rowCount: number;
    fileSize: string;
    createTime: string;
  }
  
  interface ExcelRow {
    [key: string]: any;
  }
  
  interface TemplateInfo {
    fileName: string;
    sheetCount: number;
    worksheets: TemplateWorksheet[];
  }
  
  interface TemplateWorksheet {
    name: string;
    headers: string[];
    data: ExcelRow[];
    columns: any[];
    headerRow: number;
    dataStartRow: number;
    dataCount: number;
    originalWorksheet?: ExcelJS.Worksheet; // 保存原始工作表引用
  }
  
  // 日期格式化函数
  const formatCellValue = (value: any): any => {
    if (value === null || value === undefined) {
      return '';
    }
    
    // 如果是ExcelJS单元格对象，提取值
    if (value && typeof value === 'object' && 'value' in value) {
      value = value.value;
    }
    
    // 如果是公式对象，提取计算结果
    if (value && typeof value === 'object' && 'result' in value) {
      value = value.result;
    }
    
    // 如果是共享公式，提取值
    if (value && typeof value === 'object' && 'formula' in value) {
      // 如果有计算结果，使用计算结果
      if (value.result !== undefined) {
        value = value.result;
      } else {
        // 否则返回空字符串，避免公式错误
        return '';
      }
    }
    
    // 处理Date对象
    if (value instanceof Date) {
      return dayjs(value).format('YYYY-MM-DD');
    }
    
    // 处理ExcelJS的Date对象
    if (value && typeof value === 'object' && value.constructor && value.constructor.name === 'Date') {
      return dayjs(value).format('YYYY-MM-DD');
    }
    
    // 处理时间戳
    if (typeof value === 'number' && value > 1000000000000) {
      return dayjs(value).format('YYYY-MM-DD');
    }
    
    // 处理字符串格式的日期
    if (typeof value === 'string' && value.includes('GMT')) {
      try {
        const date = new Date(value);
        if (!isNaN(date.getTime())) {
          return dayjs(date).format('YYYY-MM-DD');
        }
      } catch (e) {
        // 如果解析失败，返回原值
      }
    }
    
    // 确保返回纯值，不包含公式
    const stringValue = value.toString();
    if (stringValue.startsWith('=')) {
      // 如果是公式，返回空字符串
      return '';
    }
    
    // 检查是否是无效的对象字符串
    if (stringValue === '[object Object]') {
      return '0';
    }
    
    // 特殊处理0值，确保0值不会被错误处理
    if (value === 0 || value === '0' || stringValue === '0') {
      return '0';
    }
    
    // 处理数值格式化
    return formatNumberValue(stringValue);
  };
  
  // 响应式数据
  const fileList = ref<UploadFile[]>([]);
  const loadingColumns = ref(false);
  const splitting = ref(false);
  const availableColumns = ref<string[]>([]);
  const splitResults = ref<SplitResult[]>([]);
  
  // Excel预览相关数据
  const excelData = ref<ExcelRow[]>([]);
  const excelColumns = ref<string[]>([]);
  const currentFile = ref<UploadFile | null>(null);
  const fullPreviewVisible = ref(false);
  const institutionCount = ref(0);
  
  // 按机构分组的数据
  const groupedPreviewData = ref<{ [key: string]: ExcelRow[] }>({});
  const institutionNames = ref<string[]>([]);
  const activeInstitutionTab = ref<string>('');
  
  // 预览相关数据
  const previewModalVisible = ref(false);
  const previewInstitutionData = ref<ExcelRow[]>([]);
  const previewInstitutionName = ref('');
  
  // 批量下载相关数据
  const downloadingAll = ref(false);
  
  // 有效列映射（原始列号到过滤后列号的映射）
  const validColumnsMap = ref<number[]>([]);
  
  // 模板相关数据
  const templateFileList = ref<UploadFile[]>([]);
  const templateInfo = ref<TemplateInfo | null>(null);
  const templatePreviewVisible = ref(false);
  const templatePreviewLoading = ref(false);
  const templatePreviewData = ref<ExcelRow[]>([]);
  const templatePreviewColumns = ref<TableColumnsType<any>>([]);
  
  // 分表配置
  const splitConfig = reactive<SplitConfig>({});
  
  // 表格列配置
  const resultColumns = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
      width: 60
    },
    {
      title: '机构名称',
      dataIndex: 'institutionName',
      key: 'institutionName',
      width: 200,
      ellipsis: true
    },
    {
      title: '文件名',
      dataIndex: 'fileName',
      key: 'fileName',
      ellipsis: true
    },
    {
      title: '行数',
      dataIndex: 'rowCount',
      key: 'rowCount',
      width: 80
    },
    {
      title: '文件大小',
      dataIndex: 'fileSize',
      key: 'fileSize',
      width: 100
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150
    },
    {
      title: '操作',
      key: 'action',
      width: 120
    }
  ];
  
  // 预览表格列配置
  const previewColumns = computed(() => {
    const columns: TableColumnsType<any> = [];
    
    // 如果有模板，使用模板的列配置
    if (templateInfo.value && previewInstitutionData.value.length > 0) {
      // 检查预览数据是否包含模板格式的数据
      const firstRow = previewInstitutionData.value[0];
      if (firstRow && firstRow.key && (firstRow.key as string).startsWith('financial_')) {
        // 金融资产表格式
        const financialTemplate = templateInfo.value.worksheets.find(ws => ws.name === '金融资产');
        if (financialTemplate) {
          financialTemplate.headers.forEach((header, index) => {
            const colKey = `col${index + 1}`;
            // 检查该列是否有数据
            const hasData = previewInstitutionData.value.some(record => 
              record[colKey] !== undefined && 
              record[colKey] !== null && 
              record[colKey] !== '' &&
              String(record[colKey]).trim() !== ''
            );
            
            if (hasData) {
              columns.push({
                title: header,
                dataIndex: colKey,
                key: colKey,
                width: 150,
                ellipsis: true,
                align: 'center',
                customCell: (record: any) => {
                  return {
                    innerHTML: formatCellValue(record[colKey])
                  };
                }
              } as any);
            }
          });
          return columns;
        }
      } else if (firstRow && firstRow.key && (firstRow.key as string).startsWith('customer_')) {
        // 客户表格式
        const customerTemplate = templateInfo.value.worksheets.find(ws => ws.name === '客户');
        if (customerTemplate) {
          customerTemplate.headers.forEach((header, index) => {
            const colKey = `col${index + 1}`;
            // 检查该列是否有数据
            const hasData = previewInstitutionData.value.some(record => 
              record[colKey] !== undefined && 
              record[colKey] !== null && 
              record[colKey] !== '' &&
              String(record[colKey]).trim() !== ''
            );
            
            if (hasData) {
              columns.push({
                title: header,
                dataIndex: colKey,
                key: colKey,
                width: 150,
                ellipsis: true,
                align: 'center',
                customCell: (record: any) => {
                  return {
                    innerHTML: formatCellValue(record[colKey])
                  };
                }
              } as any);
            }
          });
          return columns;
        }
      }
    }
    
    // 默认使用原始Excel列配置
    excelColumns.value.forEach((column, index) => {
      // 使用有效列映射找到原始列号
      const originalColNumber = validColumnsMap.value[index];
      const colKey = `col${originalColNumber}`;
      
      // 检查该列是否有数据（使用excelData而不是previewInstitutionData）
      const hasData = excelData.value.some(record => 
        record[colKey] !== undefined && 
        record[colKey] !== null && 
        record[colKey] !== '' &&
        String(record[colKey]).trim() !== ''
      );
      
      if (hasData) {
        columns.push({
          title: column,
          dataIndex: colKey,
          key: colKey,
          width: 120,
          ellipsis: true,
          align: 'center',
          customCell: (record: any) => {
            return {
              innerHTML: formatCellValue(record[colKey])
            };
          }
        } as any);
      }
    });
    
    return columns;
  });
  
  // 全屏预览表格列配置
  const fullPreviewColumns = computed(() => {
    const columns = [
      {
        title: '序号',
        key: 'index',
        width: 80,
        fixed: 'left'
      }
    ];
    
    excelColumns.value.forEach((column, index) => {
      // 使用有效列映射找到原始列号
      const originalColNumber = validColumnsMap.value[index];
      const colKey = `col${originalColNumber}`;
      
      // 检查该列是否有数据（在所有机构的数据中）
      const hasData = Object.values(groupedPreviewData.value).some(institutionData => 
        institutionData.some(record => 
          record[colKey] !== undefined && 
          record[colKey] !== null && 
          record[colKey] !== '' &&
          String(record[colKey]).trim() !== ''
        )
      );
      
      if (hasData) {
        columns.push({
          title: column,
          dataIndex: colKey,
          key: colKey,
          width: 150,
          ellipsis: true,
          align: 'center',
          customCell: (record: any) => {
            return {
              innerHTML: formatCellValue(record[colKey])
            };
          }
        } as any);
      }
    });
    
    return columns;
  });
  
  
  // 计算属性
  const canSplit = computed(() => {
    return fileList.value.length > 0 && 
           excelData.value.length > 0 && 
           templateInfo.value !== null;
  });
  
  
  // 文件上传前处理
  const beforeUpload = (file: File) => {
    const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                    file.type === 'application/vnd.ms-excel';
    
    if (!isExcel) {
      message.error('只能上传Excel文件！');
      return false;
    }
    
    const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
      message.error('文件大小不能超过10MB！');
      return false;
    }
    
    return false; // 阻止自动上传
  };
  
  // 文件上传变化处理
  const handleUploadChange = (info: any) => {
    if (info.fileList.length > 0) {
      currentFile.value = info.fileList[0];
      // 解析Excel文件
      parseExcelFile(info.fileList[0].originFileObj);
    }
  };
  
  // 移除文件处理
  const handleRemove = (_file: UploadFile) => {
    // 清空Excel预览数据
    excelData.value = [];
    excelColumns.value = [];
    availableColumns.value = [];
    splitResults.value = [];
    currentFile.value = null;
    institutionCount.value = 0;
    validColumnsMap.value = [];
    return true;
  };
  
  // 解析Excel文件
  const parseExcelFile = async (file: File) => {
    loadingColumns.value = true;
    try {
      // 创建文件读取器
      const reader = new FileReader();
  
      // 读取文件内容
      const buffer = await new Promise<ArrayBuffer>((resolve, reject) => {
        reader.onload = (e) => {
          if (e.target?.result instanceof ArrayBuffer) {
            resolve(e.target.result);
          } else {
            reject(new Error('无法读取文件内容'));
          }
        };
        reader.onerror = reject;
        reader.readAsArrayBuffer(file);
      });
  
      // 使用exceljs处理文件
      const workbook = new ExcelJS.Workbook();
      await workbook.xlsx.load(buffer, {
        ignoreNodes: ['sharedStrings']
      });
  
      // 获取第一个工作表
      const worksheet = workbook.worksheets[0];
      if (!worksheet) {
        throw new Error('Excel文件中没有找到工作表');
      }
  
      // 解析表头（第一行）
      const allHeaders: string[] = [];
      const headerRow = worksheet.getRow(1);
      
      if (!headerRow || !headerRow.values || !Array.isArray(headerRow.values)) {
        throw new Error('无法读取Excel表头');
      }
  
      // 先解析所有表头
      for (let colNumber = 1; colNumber < (headerRow.values as any[]).length; colNumber++) {
        const cellValue = (headerRow.values as any[])[colNumber];
        const headerName = cellValue?.toString()?.trim() || `列${colNumber}`;
        allHeaders[colNumber - 1] = headerName;
      }
  
      // 解析数据行
      const data: ExcelRow[] = [];
      let dataRowCount = 0;
      
      worksheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {
        // 跳过表头行
        if (rowNumber === 1) return;
        
        const rowData: ExcelRow = { key: `row_${rowNumber}` };
        let hasData = false;
        
        for (let colNumber = 1; colNumber <= allHeaders.length; colNumber++) {
          const cell = row.getCell(colNumber);
          let cellValue = null;
          
          try {
            // 尝试获取单元格的值，优先获取计算结果
            if (cell.value !== null && cell.value !== undefined) {
              cellValue = cell.value;
            } else if (cell.result !== null && cell.result !== undefined) {
              cellValue = cell.result;
            } else if (cell.text) {
              cellValue = cell.text;
            }
          } catch (error) {
            // 如果获取值失败，跳过这个单元格
            console.warn(`获取单元格 ${colNumber} 的值失败:`, error);
            cellValue = null;
          }
          
          const colKey = `col${colNumber}`;
          // 特殊列：证件号码 原样作为文本保留（避免被当成数字）
          const headerNameForCol = allHeaders[colNumber - 1] || '';
          if (headerNameForCol.includes('证件号码')) {
            const rawText = (cell && typeof cell.text !== 'undefined') ? cell.text : cellValue;
            rowData[colKey] = rawText !== null && rawText !== undefined ? String(rawText) : '';
          } else {
            // 其他列按原有规则格式化
            rowData[colKey] = formatCellValue(cellValue);
          }
          
          // 检查是否有非空数据
          if (cellValue !== null && cellValue !== undefined && cellValue !== '') {
            hasData = true;
          }
        }
        
        // 只添加有数据的行
        if (hasData) {
          data.push(rowData);
          dataRowCount++;
        }
      });
  
      // 过滤掉没有数据的列
      const validColumns: number[] = [];
      const validHeaders: string[] = [];
      const tableColumns: TableColumnsType<any> = [];
      
      // 定义需要隐藏的列（即使有数据也不显示）
      const hiddenColumns = [
        '序号',
        '关注'
      ];
      
      allHeaders.forEach((header, index) => {
        const colNumber = index + 1;
        const colKey = `col${colNumber}`;
        
        // 检查是否是需要隐藏的列
        const isHiddenColumn = hiddenColumns.some(hiddenCol => 
          header.includes(hiddenCol) || hiddenCol.includes(header)
        );
        
        // 如果是需要隐藏的列，则跳过
        if (isHiddenColumn) {
          console.log(`隐藏列: ${header}`);
          return;
        }
        
        // 检查这一列是否有非空数据
        const hasData = data.some(row => {
          const value = row[colKey];
          return value !== null && value !== undefined && value !== '' && 
                 value.toString().trim() !== '';
        });
        
        // 如果有数据，则包含在有效列中
        if (hasData) {
          validColumns.push(colNumber);
          validHeaders.push(header);
          tableColumns.push({
            title: header,
            dataIndex: colKey,
            key: colKey,
            width: 120,
            ellipsis: true,
            align: 'center',
            customCell: (record: any) => {
              return {
                innerHTML: formatCellValue(record[colKey])
              };
            }
          });
        }
      });
      
      console.log('有效列索引:', validColumns);
      console.log('有效列名:', validHeaders);
      console.log('过滤前总列数:', allHeaders.length);
      console.log('过滤后有效列数:', validHeaders.length);
  
      // 更新数据
      excelColumns.value = validHeaders;
      excelData.value = data;
      availableColumns.value = validHeaders;
      validColumnsMap.value = validColumns;
      
      // 设置机构数量为1（表示全部数据）
      institutionCount.value = 1;
      
      message.success(`Excel文件解析成功，共${validHeaders.length}列（过滤掉${allHeaders.length - validHeaders.length}个空列），${data.length}行数据`);
    } catch (error) {
      message.error('Excel文件解析失败');
      console.error('Excel解析错误:', error);
    } finally {
      loadingColumns.value = false;
    }
  };
  
  // 格式化文件大小
  const formatFileSize = (size?: number) => {
    if (!size) return '0 B';
    const units = ['B', 'KB', 'MB', 'GB'];
    let index = 0;
    let fileSize = size;
    
    while (fileSize >= 1024 && index < units.length - 1) {
      fileSize /= 1024;
      index++;
    }
    
    return `${fileSize.toFixed(2)} ${units[index]}`;
  };
  
  // 显示全屏预览
  const showFullPreview = () => {
    // 将所有数据放在一个分组中
    groupedPreviewData.value = { '全部数据': excelData.value };
    institutionNames.value = ['全部数据'];
    activeInstitutionTab.value = '全部数据';
    
    fullPreviewVisible.value = true;
  };
  
  // 刷新预览
  const refreshPreview = () => {
    if (currentFile.value?.originFileObj) {
      parseExcelFile(currentFile.value.originFileObj);
    }
  };
  
  // 开始分表
  const handleSplit = async () => {
    if (!canSplit.value) {
      message.warning('请完善分表配置');
      return;
    }
  
    splitting.value = true;
    try {
      // 模拟分表处理
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      // 生成分表结果（单个文件）
      const results: SplitResult[] = [{
        key: '1',
        institutionName: '全部数据',
        fileName: `${splitConfig.bankName || '平安银行-良庆'}-${new Date().toISOString().slice(0, 10).replace(/-/g, '')}-${excelData.value.length}.xlsx`,
        rowCount: excelData.value.length,
        fileSize: formatFileSize(excelData.value.length * 100), // 估算文件大小
        createTime: new Date().toLocaleString()
      }];
      
      splitResults.value = results;
      
      // 显示分表成功消息
      message.success(`分表处理完成！使用模板格式生成1个文件，包含${excelData.value.length}行数据`);
    } catch (error) {
      message.error('分表处理失败');
      console.error('分表处理错误:', error);
    } finally {
      splitting.value = false;
    }
  };
  
  // 重置配置
  const resetConfig = () => {
    splitResults.value = [];
  };
  
  // 下载文件
  const downloadFile = async (record: SplitResult) => {
    try {
      // 使用全部数据
      const allData = excelData.value;
      
      if (allData.length === 0) {
        message.error('未找到数据');
        return;
      }
      
      // 创建新的工作簿
      const workbook = new ExcelJS.Workbook();
      
      // 使用模板格式生成完整的工作簿
      if (templateInfo.value) {
        await generateWorkbookWithTemplate(workbook, allData, templateInfo.value, '全部数据');
      } else {
        message.error('未找到分表模板，无法进行分表操作');
        return;
      }
      
      // 生成Excel文件，禁用共享公式
      const buffer = await workbook.xlsx.writeBuffer({
        useSharedStrings: false,
        useStyles: true
      });
      
      // 创建下载链接
      const blob = new Blob([buffer], { 
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
      });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = record.fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error('下载文件失败:', error);
      message.error('下载文件失败');
    }
  };
  
  
  // 使用模板格式生成完整的工作簿
  const generateWorkbookWithTemplate = async (workbook: ExcelJS.Workbook, institutionData: ExcelRow[], template: TemplateInfo, institutionName: string) => {
    // 创建所有工作表：金融资产、物业资产、调解场景、诉讼场景、客户、联系人、担保人、分案关系
    const financialWorksheet = workbook.addWorksheet('金融资产');
    const propertyWorksheet = workbook.addWorksheet('物业资产');
    const mediationWorksheet = workbook.addWorksheet('调解场景');
    const litigationWorksheet = workbook.addWorksheet('诉讼场景');
    const customerWorksheet = workbook.addWorksheet('客户');
    const contactWorksheet = workbook.addWorksheet('联系人');
    const guarantorWorksheet = workbook.addWorksheet('担保人');
    const relationshipWorksheet = workbook.addWorksheet('分案关系');
    
    // 处理金融资产表
    if (template.worksheets && template.worksheets.length > 0) {
      const financialTemplate = template.worksheets.find(ws => ws.name === '金融资产');
      if (financialTemplate) {
        await fillWorksheetWithTemplate(financialWorksheet, institutionData, financialTemplate, 3, 4, institutionName);
      }
    }
    
    // 处理物业资产表 - 原封不动复制模板
    const propertyTemplate = template.worksheets.find(ws => ws.name === '物业资产');
    if (propertyTemplate && propertyTemplate.originalWorksheet) {
      copyWorksheetStyle(propertyTemplate.originalWorksheet, propertyWorksheet);
    }
    
    // 处理调解场景表 - 原封不动复制模板
    const mediationTemplate = template.worksheets.find(ws => ws.name === '调解场景');
    if (mediationTemplate && mediationTemplate.originalWorksheet) {
      copyWorksheetStyle(mediationTemplate.originalWorksheet, mediationWorksheet);
    }
    
    // 处理诉讼场景表 - 原封不动复制模板
    const litigationTemplate = template.worksheets.find(ws => ws.name === '诉讼场景');
    if (litigationTemplate && litigationTemplate.originalWorksheet) {
      copyWorksheetStyle(litigationTemplate.originalWorksheet, litigationWorksheet);
    }
    
    // 处理客户表
    const customerTemplate = template.worksheets.find(ws => ws.name === '客户');
    if (customerTemplate) {
      await fillWorksheetWithTemplate(customerWorksheet, institutionData, customerTemplate, 3, 4, institutionName);
    }
    
    // 处理联系人表 - 原封不动复制模板
    const contactTemplate = template.worksheets.find(ws => ws.name === '联系人');
    if (contactTemplate && contactTemplate.originalWorksheet) {
      copyWorksheetStyle(contactTemplate.originalWorksheet, contactWorksheet);
    }
    
    // 处理担保人表 - 原封不动复制模板
    const guarantorTemplate = template.worksheets.find(ws => ws.name === '担保人');
    if (guarantorTemplate && guarantorTemplate.originalWorksheet) {
      copyWorksheetStyle(guarantorTemplate.originalWorksheet, guarantorWorksheet);
    }
    
    // 处理分案关系表
    const relationshipTemplate = template.worksheets.find(ws => ws.name === '分案关系');
    if (relationshipTemplate && relationshipTemplate.originalWorksheet) {
      // 如果有模板，复制样式并填充数据
      copyWorksheetStyle(relationshipTemplate.originalWorksheet, relationshipWorksheet);
      await fillRelationshipData(relationshipWorksheet, institutionData);
    } else {
      // 如果没有模板，创建基本格式并填充数据
      await createEmptyRelationshipWorksheet(relationshipWorksheet, institutionData);
    }
    
    // 自动调整所有工作表的列宽（仅对没有预设宽度的列）
    [financialWorksheet, propertyWorksheet, mediationWorksheet, litigationWorksheet, 
     customerWorksheet, contactWorksheet, guarantorWorksheet, relationshipWorksheet].forEach(worksheet => {
      for (let i = 0; i < worksheet.columns.length; i++) {
        const column = worksheet.columns[i];
        if (column && column.eachCell && !column.width) {
          let maxLength = 0;
          column.eachCell({ includeEmpty: true }, (cell) => {
            const columnLength = cell.value ? cell.value.toString().length : 10;
            if (columnLength > maxLength) {
              maxLength = columnLength;
            }
          });
          column.width = Math.min(maxLength + 2, 50);
        }
      }
    });
  };
  
  // 使用模板格式填充单个工作表
  const fillWorksheetWithTemplate = async (worksheet: ExcelJS.Worksheet, institutionData: ExcelRow[], template: TemplateWorksheet, headerRowNum: number, dataStartRowNum: number, institutionName: string) => {
    // 根据工作表类型进行不同的数据填充
    if (template.name === '金融资产') {
      await fillFinancialAssetDataWithStyle(worksheet, institutionData, template, headerRowNum, dataStartRowNum, institutionName);
    } else if (template.name === '客户') {
      await fillCustomerDataWithStyle(worksheet, institutionData, template, headerRowNum, dataStartRowNum, institutionName);
    }
  };
  
  
  // 获取列键的辅助函数
  const getColumnKey = (columnName: string): string => {
    console.log(`查找列键: ${columnName}`);
    console.log('可用列名:', excelColumns.value);
    console.log('有效列映射:', validColumnsMap.value);
    
    const columnIndex = excelColumns.value.findIndex(header => 
      header.includes(columnName) || columnName.includes(header)
    );
    
    console.log(`找到的列索引: ${columnIndex}`);
    
    if (columnIndex !== -1) {
      const originalColNumber = validColumnsMap.value[columnIndex];
      const colKey = `col${originalColNumber}`;
      console.log(`返回列键: ${colKey}`);
      return colKey;
    }
    
    // 如果没找到，尝试更宽松的匹配
    const looseMatchIndex = excelColumns.value.findIndex(header => 
      header.toLowerCase().includes(columnName.toLowerCase()) || 
      columnName.toLowerCase().includes(header.toLowerCase())
    );
    
    if (looseMatchIndex !== -1) {
      const originalColNumber = validColumnsMap.value[looseMatchIndex];
      const colKey = `col${originalColNumber}`;
      console.log(`宽松匹配找到列键: ${colKey}`);
      return colKey;
    }
    
    console.warn(`未找到列: ${columnName}`);
    return '';
  };
  
  // 格式化数字值，处理浮点数精度问题
  const formatNumberValue = (value: any, columnName?: string): string => {
    console.log('formatNumberValue 输入:', value, typeof value);
    
    if (value === null || value === undefined) {
      return '';
    }
    
    // 如果已经是字符串且为数字格式，直接处理
    if (typeof value === 'string') {
      const trimmed = value.trim();
      if (trimmed === '') {
        return '';
      }
      if (trimmed === '0') {
        return '0';
      }
      // 检查是否是无效的对象字符串
      if (trimmed === '[object Object]') {
        // 对于『当前拖欠利息（元）』列，返回"0"
        if (columnName === '当前拖欠利息（元）') {
          return '0';
        }
        return '';
      }
      const numValue = parseFloat(trimmed);
      if (!isNaN(numValue)) {
        if (Number.isInteger(numValue)) {
          return numValue.toString();
        }
        const formatted = numValue.toFixed(2);
        return parseFloat(formatted).toString();
      }
      return trimmed;
    }
    
    // 如果是数字类型
    if (typeof value === 'number') {
      if (value === 0) {
        return '0';
      }
      if (Number.isInteger(value)) {
        return value.toString();
      }
      const formatted = value.toFixed(2);
      return parseFloat(formatted).toString();
    }
    
    // 如果是对象，尝试提取数值
    if (value && typeof value === 'object') {
      // 检查是否是ExcelJS单元格对象
      if ('result' in value) {
        return formatNumberValue(value.result, columnName);
      }
      if ('value' in value) {
        return formatNumberValue(value.value, columnName);
      }
      if ('text' in value) {
        return formatNumberValue(value.text, columnName);
      }
      if ('numValue' in value) {
        return formatNumberValue(value.numValue, columnName);
      }
      // 如果无法提取有效值，对于利息列返回"0"
      if (columnName === '当前拖欠利息（元）') {
        return '0';
      }
      return '';
    }
    
    // 其他情况，尝试转换为字符串
    try {
      const stringValue = value.toString();
      if (stringValue === '[object Object]') {
        // 对于利息列，返回"0"
        if (columnName === '当前拖欠利息（元）') {
          return '0';
        }
        return '';
      }
      return formatNumberValue(stringValue, columnName);
    } catch (error) {
      // 对于利息列，即使转换失败也返回"0"
      if (columnName === '当前拖欠利息（元）') {
        return '0';
      }
      return '';
    }
  };
  
  // 获取公式计算结果值的辅助函数
  const getFormulaValue = (rowData: ExcelRow, columnName: string): string => {
    const columnKey = getColumnKey(columnName);
    if (!columnKey) {
      console.warn(`未找到列键: ${columnName}`);
      return '';
    }
    
    const value = rowData[columnKey];
    if (value === null || value === undefined) {
      console.warn(`列 ${columnName} 的值为空`);
      return '';
    }
    
    console.log(`处理列 ${columnName} 的值:`, value, typeof value);
    
    // 如果是ExcelJS单元格对象，优先获取计算结果
    if (value && typeof value === 'object') {
      console.log('检测到对象类型，尝试提取值:', Object.keys(value));
      
      let extractedValue = null;
      
      // 优先获取计算结果（包括0值）
      if ('result' in value) {
        console.log('使用result属性:', value.result);
        extractedValue = value.result;
      }
      // 其次获取值（包括0值）
      else if ('value' in value) {
        console.log('使用value属性:', value.value);
        extractedValue = value.value;
      }
      // 最后获取文本（包括0值）
      else if ('text' in value) {
        console.log('使用text属性:', value.text);
        extractedValue = value.text;
      }
      // 检查是否有其他数值属性（包括0值）
      else if ('numValue' in value) {
        console.log('使用numValue属性:', value.numValue);
        extractedValue = value.numValue;
      }
      // 如果对象没有上述属性，尝试直接转换为字符串
      else {
        try {
          const stringValue = value.toString();
          if (stringValue !== '[object Object]') {
            console.log('使用toString():', stringValue);
            extractedValue = stringValue;
          } else {
            console.warn('对象转换为字符串失败，返回空字符串');
            extractedValue = '';
          }
        } catch (error) {
          console.warn('转换对象为字符串失败:', error);
          extractedValue = '';
        }
      }
      
      if (extractedValue !== null && extractedValue !== undefined) {
        // 对数值进行格式化处理
        console.log('提取到的值:', extractedValue, typeof extractedValue);
        return formatNumberValue(extractedValue, columnName);
      }
      
      // 如果还是对象，尝试JSON序列化
      try {
        const jsonString = JSON.stringify(value);
        if (jsonString !== '{}' && jsonString !== 'null') {
          console.log('使用JSON序列化:', jsonString);
          return formatNumberValue(jsonString, columnName);
        }
      } catch (error) {
        console.warn('JSON序列化失败:', error);
      }
      
      // 对于『当前拖欠利息（元）』列，如果无法提取有效值，返回"0"
      if (columnName === '当前拖欠利息（元）') {
        console.warn('无法从对象中提取有效值，对于利息列返回"0"');
        return '0';
      }
      
      console.warn('无法从对象中提取有效值，返回空字符串');
      return '';
    }
    
    // 如果是字符串且以=开头（公式），尝试提取数字
    const stringValue = value.toString();
    if (stringValue.startsWith('=')) {
      console.log('检测到公式字符串:', stringValue);
      // 尝试从公式中提取数字（简单处理）
      const numberMatch = stringValue.match(/(\d+\.?\d*)/);
      if (numberMatch) {
        console.log('从公式中提取数字:', numberMatch[1]);
        return formatNumberValue(numberMatch[1], columnName);
      }
      return '';
    }
    
    // 普通值处理
    console.log('使用普通值处理:', value);
    return formatNumberValue(value, columnName);
  };
  
  // 创建分案关系工作表并填充数据
  const createEmptyRelationshipWorksheet = async (worksheet: ExcelJS.Worksheet, institutionData: ExcelRow[]) => {
    // 设置表头（第1行）
    const headerRow = worksheet.getRow(1);
    headerRow.getCell(1).value = '*委托方合同编号';
    headerRow.getCell(2).value = '跟进人';
    
    // 设置表头样式
    headerRow.font = { bold: true };
    headerRow.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFE6F3FF' }
    };
    
    // 填充数据
    institutionData.forEach((rowData, rowIndex) => {
      const dataRow = worksheet.getRow(rowIndex + 2);
      dataRow.getCell(1).value = formatCellValue(rowData[getColumnKey('合同号')]);
      dataRow.getCell(2).value = '孙冬艳';
    });
  };

  // 填充分案关系表数据
  const fillRelationshipData = async (worksheet: ExcelJS.Worksheet, institutionData: ExcelRow[]) => {
    // 查找表头行
    let headerRowNumber = 1;
    let contractColumnNumber = 1;
    let followUpColumnNumber = 2;
    
    // 查找委托方合同编号列
    worksheet.eachRow({ includeEmpty: true }, (row, rowNumber) => {
      row.eachCell({ includeEmpty: true }, (cell, colNumber) => {
        if (cell.value && cell.value.toString().includes('委托方合同编号')) {
          headerRowNumber = rowNumber;
          contractColumnNumber = colNumber;
        }
        if (cell.value && cell.value.toString().includes('跟进人')) {
          followUpColumnNumber = colNumber;
        }
      });
    });
    
    // 填充数据
    institutionData.forEach((rowData, rowIndex) => {
      const dataRow = worksheet.getRow(headerRowNumber + 1 + rowIndex);
      dataRow.getCell(contractColumnNumber).value = formatCellValue(rowData[getColumnKey('合同号')]);
      dataRow.getCell(followUpColumnNumber).value = '孙冬艳';
    });
  };
  
  
  // 预览文件
  const previewFile = async (record: SplitResult) => {
    try {
      // 使用全部数据
      const allData = excelData.value;
      
      if (allData.length === 0) {
        message.error('未找到数据');
        return;
      }
      
      // 生成模板格式的预览数据
      if (templateInfo.value) {
        await generateTemplatePreviewData(allData, '全部数据');
      } else {
        message.error('未找到分表模板，无法预览数据');
        return;
      }
      
      previewInstitutionName.value = '全部数据';
      previewModalVisible.value = true;
      
    } catch (error) {
      console.error('预览文件失败:', error);
      message.error('预览文件失败');
    }
  };
  
  // 生成模板格式的预览数据
  const generateTemplatePreviewData = async (institutionData: ExcelRow[], institutionName: string) => {
    // 默认显示金融资产表数据
    const financialTemplate = templateInfo.value?.worksheets.find(ws => ws.name === '金融资产');
    if (financialTemplate) {
      const financialData = await generateFinancialAssetPreviewData(institutionData, institutionName, financialTemplate);
      previewInstitutionData.value = financialData;
    } else {
      // 如果没有金融资产表，显示客户表
      const customerTemplate = templateInfo.value?.worksheets.find(ws => ws.name === '客户');
      if (customerTemplate) {
        const customerData = await generateCustomerPreviewData(institutionData, institutionName, customerTemplate);
        previewInstitutionData.value = customerData;
      }
    }
  };
  
  // 生成金融资产表预览数据
  const generateFinancialAssetPreviewData = async (institutionData: ExcelRow[], institutionName: string, template: TemplateWorksheet) => {
    const today = new Date();
    const todayStr = today.getFullYear().toString() + 
                     (today.getMonth() + 1).toString().padStart(2, '0') + 
                     today.getDate().toString().padStart(2, '0');
    
    // 回电号码映射
    const phoneMapping: { [key: string]: string } = {
      '南宁联信': '0771-2535939',
      '广西儒晓': '0771-4820637',
      '柳州恒运': '0772-3434714',
      '南宁恒运': '0771-4817669，19943048011',
      '南宁光禾汇金': '0771-3940804',
      '南宁恒银': '0771-2425710',
      '南宁天目': '0771-2535954',
      '南宁赟途': '0771-2503121',
      '钦州赟途': '0777-2184584',
      '钦州儒晓': '0777-2152802'
    };
    
    const previewData: ExcelRow[] = [];
    
    institutionData.forEach((rowData, rowIndex) => {
      const dataNumber = (rowIndex + 1).toString().padStart(3, '0');
      const contractNumber = `${splitConfig.bankName || '平安银行-良庆'}-${institutionName}-${todayStr}-${institutionData.length}-${dataNumber}`;
      
      const previewRow: ExcelRow = { key: `financial_${rowIndex}` };
      
      template.headers.forEach((templateHeader, templateIndex) => {
        const colKey = `col${templateIndex + 1}`;
        let cellValue = '';
        
        switch (templateHeader) {
          case '*产品名称':
            cellValue = '平安银行-良庆';
            break;
          case '*委托方合同编号':
            cellValue = formatCellValue(rowData[getColumnKey('合同号')]);
            break;
          case '*放款日期':
          case '还款日期':
            cellValue = '20200101';
            break;
          case '逾期天数':
            cellValue = formatCellValue(rowData[getColumnKey('当前逾期天数')]);
            break;
          case '*当期天数':
            cellValue = '30';
            break;
          case '*委案金额':
            cellValue = formatCellValue(rowData[getColumnKey('当前拖欠总额（元）')]);
            break;
          case '*逾期本金':
            cellValue = formatCellValue(rowData[getColumnKey('当前拖欠本金（元）')]);
            break;
          case '逾期利息':
            cellValue = formatCellValue(rowData[getColumnKey('当前拖欠利息（元）')]);
            break;
          case '逾期服务费':
            cellValue = formatCellValue(rowData[getColumnKey('当前拖欠复利（元）')]);
            break;
          case '备注:客户ID':
            cellValue = formatCellValue(rowData[getColumnKey('客户号')]);
            break;
          case '备注:数据来源':
            cellValue = formatCellValue(rowData[getColumnKey('数据来源')]);
            break;
          case '备注:业务类型':
            cellValue = formatCellValue(rowData[getColumnKey('业务类型')]);
            break;
          case '备注:当前贷款余额（元）':
            cellValue = formatCellValue(rowData[getColumnKey('当前贷款余额（元）')]);
            break;
          case '备注:委托标的（元）':
            cellValue = formatCellValue(rowData[getColumnKey('委托标的（元）')]);
            break;
          default:
            cellValue = '';
        }
        
        previewRow[colKey] = cellValue;
      });
      
      previewData.push(previewRow);
    });
    
    return previewData;
  };
  
  // 生成客户表预览数据
  const generateCustomerPreviewData = async (institutionData: ExcelRow[], institutionName: string, template: TemplateWorksheet) => {
    const today = new Date();
    const todayStr = today.getFullYear().toString() + 
                     (today.getMonth() + 1).toString().padStart(2, '0') + 
                     today.getDate().toString().padStart(2, '0');
    
    const previewData: ExcelRow[] = [];
    
    institutionData.forEach((rowData, rowIndex) => {
      const dataNumber = (rowIndex + 1).toString().padStart(3, '0');
      const contractNumber = `${splitConfig.bankName || '平安银行-良庆'}-${institutionName}-${todayStr}-${institutionData.length}-${dataNumber}`;
      
      const previewRow: ExcelRow = { key: `customer_${rowIndex}` };
      
      template.headers.forEach((templateHeader, templateIndex) => {
        const colKey = `col${templateIndex + 1}`;
        let cellValue = '';
        
        switch (templateHeader) {
          case '*委托方合同编号':
            cellValue = formatCellValue(rowData[getColumnKey('合同号')]);
            break;
          case '姓名':
            cellValue = formatCellValue(rowData[getColumnKey('客户名称')]);
            break;
          case '联系电话':
            cellValue = formatCellValue(rowData[getColumnKey('手机号码')]);
            break;
          case '证件号码':
            // 原样作为文本，不做数值格式化
            cellValue = String(rowData[getColumnKey('证件号码')] ?? '');
            break;
          case '户籍地址':
            cellValue = formatCellValue(rowData[getColumnKey('家庭地址（省市区/县）')]);
            break;
          default:
            cellValue = '';
        }
        
        previewRow[colKey] = cellValue;
      });
      
      previewData.push(previewRow);
    });
    
    return previewData;
  };
  
  // 复制模板样式到新工作表
  const copyWorksheetStyle = (sourceWorksheet: ExcelJS.Worksheet, targetWorksheet: ExcelJS.Worksheet) => {
    // 复制列宽
    sourceWorksheet.columns.forEach((sourceCol, index) => {
      if (sourceCol.width) {
        targetWorksheet.getColumn(index + 1).width = sourceCol.width;
      }
    });
  
    // 复制行高
    sourceWorksheet.eachRow({ includeEmpty: true }, (sourceRow, rowNumber) => {
      if (sourceRow.height) {
        targetWorksheet.getRow(rowNumber).height = sourceRow.height;
      }
    });
  
    // 复制单元格样式和合并
    sourceWorksheet.eachRow({ includeEmpty: true }, (sourceRow, rowNumber) => {
      const targetRow = targetWorksheet.getRow(rowNumber);
      
      sourceRow.eachCell({ includeEmpty: true }, (sourceCell, colNumber) => {
        const targetCell = targetRow.getCell(colNumber);
        
        // 复制单元格样式
        if (sourceCell.style) {
          targetCell.style = JSON.parse(JSON.stringify(sourceCell.style));
        }
        
        // 复制单元格值（如果存在）
        if (sourceCell.value !== null && sourceCell.value !== undefined) {
          targetCell.value = sourceCell.value;
        }
      });
    });
  
    // 复制合并单元格
    sourceWorksheet.model.merges?.forEach(merge => {
      targetWorksheet.mergeCells(merge);
    });
  
    // 复制数据验证（如果支持）
    try {
      const sourceDataValidations = (sourceWorksheet as any).dataValidations;
      if (sourceDataValidations) {
        // 检查是否是数组或可迭代对象
        if (Array.isArray(sourceDataValidations)) {
          sourceDataValidations.forEach((validation: any) => {
            (targetWorksheet as any).dataValidations.add(validation);
          });
        } else if (sourceDataValidations.forEach) {
          sourceDataValidations.forEach((validation: any) => {
            (targetWorksheet as any).dataValidations.add(validation);
          });
        } else if (sourceDataValidations.values) {
          // 如果是Map或Set类型
          for (const validation of sourceDataValidations.values()) {
            (targetWorksheet as any).dataValidations.add(validation);
          }
        }
      }
    } catch (error) {
      console.warn('复制数据验证失败:', error);
    }
  
    // 复制条件格式（如果支持）
    try {
      const sourceConditionalFormattings = (sourceWorksheet as any).conditionalFormattings;
      if (sourceConditionalFormattings) {
        // 检查是否是数组或可迭代对象
        if (Array.isArray(sourceConditionalFormattings)) {
          sourceConditionalFormattings.forEach((conditionalFormatting: any) => {
            (targetWorksheet as any).conditionalFormattings.add(conditionalFormatting);
          });
        } else if (sourceConditionalFormattings.forEach) {
          sourceConditionalFormattings.forEach((conditionalFormatting: any) => {
            (targetWorksheet as any).conditionalFormattings.add(conditionalFormatting);
          });
        } else if (sourceConditionalFormattings.values) {
          // 如果是Map或Set类型
          for (const conditionalFormatting of sourceConditionalFormattings.values()) {
            (targetWorksheet as any).conditionalFormattings.add(conditionalFormatting);
          }
        }
      }
    } catch (error) {
      console.warn('复制条件格式失败:', error);
    }
  
    // 复制批注（注释）
    try {
      copyComments(sourceWorksheet, targetWorksheet);
    } catch (error) {
      console.warn('复制批注失败:', error);
    }
  };
  
  // 复制批注（注释）的专用函数
  const copyComments = (sourceWorksheet: ExcelJS.Worksheet, targetWorksheet: ExcelJS.Worksheet) => {
    sourceWorksheet.eachRow({ includeEmpty: true }, (sourceRow, rowNumber) => {
      sourceRow.eachCell({ includeEmpty: true }, (sourceCell, colNumber) => {
        if (sourceCell.note) {
          const targetCell = targetWorksheet.getCell(rowNumber, colNumber);
          
          try {
            // 深度复制批注对象
            const noteData = JSON.parse(JSON.stringify(sourceCell.note));
            
            // 创建新的批注对象
            const newNote: any = {};
            
            // 复制基本属性（使用类型断言）
            const sourceNote = sourceCell.note as any;
            if (sourceNote.texts) {
              newNote.texts = sourceNote.texts;
            }
            if (sourceNote.margins) {
              newNote.margins = sourceNote.margins;
            }
            if (sourceNote.size) {
              newNote.size = sourceNote.size;
            }
            if (sourceNote.editAs) {
              newNote.editAs = sourceNote.editAs;
            }
            
            // 复制其他可能的属性
            Object.keys(noteData).forEach(key => {
              if (!['texts', 'margins', 'size', 'editAs'].includes(key)) {
                newNote[key] = noteData[key];
              }
            });
            
            // 设置批注
            targetCell.note = newNote;
            
          } catch (noteError) {
            console.warn(`复制单元格 ${rowNumber},${colNumber} 的批注失败:`, noteError);
            
            // 如果深度复制失败，尝试简单复制
            try {
              const sourceNote = sourceCell.note as any;
              targetCell.note = {
                texts: sourceNote.texts || [],
                margins: sourceNote.margins || {},
                editAs: sourceNote.editAs || 'oneCell',
                ...(sourceNote.size && { size: sourceNote.size })
              } as any;
            } catch (simpleError) {
              console.warn(`简单复制批注也失败:`, simpleError);
            }
          }
        }
      });
    });
  };
  
  // 带样式的金融资产表数据填充
  const fillFinancialAssetDataWithStyle = async (worksheet: ExcelJS.Worksheet, institutionData: ExcelRow[], template: TemplateWorksheet, _headerRowNum: number, dataStartRowNum: number, institutionName: string) => {
    // 如果有原始工作表，先复制样式
    if (template.originalWorksheet) {
      copyWorksheetStyle(template.originalWorksheet, worksheet);
    }
  
    const today = new Date();
    const todayStr = today.getFullYear().toString() + 
                     (today.getMonth() + 1).toString().padStart(2, '0') + 
                     today.getDate().toString().padStart(2, '0');
    
    // 回电号码映射
    const phoneMapping: { [key: string]: string } = {
      '南宁联信': '0771-2535939',
      '广西儒晓': '0771-4820637',
      '柳州恒运': '0772-3434714',
      '南宁恒运': '0771-4817669，19943048011',
      '南宁光禾汇金': '0771-3940804',
      '南宁恒银': '0771-2425710',
      '南宁天目': '0771-2535954',
      '南宁赟途': '0771-2503121',
      '钦州赟途': '0777-2184584',
      '钦州儒晓': '0777-2152802'
    };
    
    // 添加数据行
    institutionData.forEach((rowData, rowIndex) => {
      const dataRow = worksheet.getRow(dataStartRowNum + rowIndex);
      const dataNumber = (rowIndex + 1).toString().padStart(3, '0');
      const contractNumber = `${splitConfig.bankName || '平安银行-良庆'}-${institutionName}-${todayStr}-${institutionData.length}-${dataNumber}`;
      
      template.headers.forEach((templateHeader, templateIndex) => {
        const cell = dataRow.getCell(templateIndex + 1);
        let cellValue = '';
        
        switch (templateHeader) {
          case '*产品名称':
            cellValue = '平安银行-良庆';
            break;
          case '*委托方合同编号':
            cellValue = formatCellValue(rowData[getColumnKey('合同号')]);
            break;
          case '*放款日期':
          case '还款日期':
            cellValue = '20200101';
            break;
          case '逾期天数':
            cellValue = formatCellValue(rowData[getColumnKey('当前逾期天数')]);
            break;
          case '*当期天数':
            cellValue = '30';
            break;
          case '*委案金额':
            cellValue = formatCellValue(rowData[getColumnKey('当前拖欠总额（元）')]);
            break;
          case '*逾期本金':
            cellValue = formatCellValue(rowData[getColumnKey('当前拖欠本金（元）')]);
            break;
          case '逾期利息':
            cellValue = formatCellValue(rowData[getColumnKey('当前拖欠利息（元）')]);
            break;
          case '逾期服务费':
            cellValue = formatCellValue(rowData[getColumnKey('当前拖欠复利（元）')]);
            break;
          case '备注:客户ID':
            cellValue = formatCellValue(rowData[getColumnKey('客户号')]);
            break;
          case '备注:数据来源':
            cellValue = formatCellValue(rowData[getColumnKey('数据来源')]);
            break;
          case '备注:业务类型':
            cellValue = formatCellValue(rowData[getColumnKey('业务类型')]);
            break;
          case '备注:当前贷款余额（元）':
            cellValue = formatCellValue(rowData[getColumnKey('当前贷款余额（元）')]);
            break;
          case '备注:委托标的（元）':
            cellValue = formatCellValue(rowData[getColumnKey('委托标的（元）')]);
            break;
          default:
            cellValue = '';
        }
        
        // 对证件号码强制写入为文本，避免科学计数法/去前导零
        if (templateHeader === '证件号码') {
          // 设置为文本格式
          cell.numFmt = '@';
          cell.value = String(cellValue ?? '');
        } else {
          cell.value = cellValue;
        }
        
        // 清除任何可能的公式引用
        if (cell.model && cell.model.formula) {
          delete cell.model.formula;
        }
      });
    });
  };
  
  // 带样式的客户表数据填充
  const fillCustomerDataWithStyle = async (worksheet: ExcelJS.Worksheet, institutionData: ExcelRow[], template: TemplateWorksheet, _headerRowNum: number, dataStartRowNum: number, institutionName: string) => {
    // 如果有原始工作表，先复制样式
    if (template.originalWorksheet) {
      copyWorksheetStyle(template.originalWorksheet, worksheet);
    }
  
    const today = new Date();
    const todayStr = today.getFullYear().toString() + 
                     (today.getMonth() + 1).toString().padStart(2, '0') + 
                     today.getDate().toString().padStart(2, '0');
    
    // 添加数据行
    institutionData.forEach((rowData, rowIndex) => {
      const dataRow = worksheet.getRow(dataStartRowNum + rowIndex);
      const dataNumber = (rowIndex + 1).toString().padStart(3, '0');
      const contractNumber = `${splitConfig.bankName || '平安银行-良庆'}-${institutionName}-${todayStr}-${institutionData.length}-${dataNumber}`;
      
      template.headers.forEach((templateHeader, templateIndex) => {
        const cell = dataRow.getCell(templateIndex + 1);
        let cellValue = '';
        
        switch (templateHeader) {
          case '*委托方合同编号':
            cellValue = formatCellValue(rowData[getColumnKey('合同号')]);
            break;
          case '姓名':
            cellValue = formatCellValue(rowData[getColumnKey('客户名称')]);
            break;
          case '联系电话':
            cellValue = formatCellValue(rowData[getColumnKey('手机号码')]);
            break;
          case '证件号码':
            // 原样作为文本，不做数值格式化
            cellValue = String(rowData[getColumnKey('证件号码')] ?? '');
            break;
          case '户籍地址':
            cellValue = formatCellValue(rowData[getColumnKey('家庭地址（省市区/县）')]);
            break;
          default:
            cellValue = '';
        }
        
        // 对证件号码强制写入为文本
        if (templateHeader === '证件号码') {
          cell.numFmt = '@';
          cell.value = String(cellValue ?? '');
        } else {
          cell.value = cellValue;
        }
        
        // 清除任何可能的公式引用
        if (cell.model && cell.model.formula) {
          delete cell.model.formula;
        }
      });
    });
  };
  
  // 获取预览表标题
  const getPreviewTableTitle = () => {
    if (previewInstitutionData.value.length > 0) {
      const firstRow = previewInstitutionData.value[0];
      if (firstRow && firstRow.key && (firstRow.key as string).startsWith('financial_')) {
        return '金融资产表';
      } else if (firstRow && firstRow.key && (firstRow.key as string).startsWith('customer_')) {
        return '客户表';
      }
    }
    return '数据';
  };
  
  // 批量下载所有文件
  const downloadAllFiles = async () => {
    if (splitResults.value.length === 0) {
      message.warning('没有可下载的文件');
      return;
    }
    
    downloadingAll.value = true;
    try {
      let successCount = 0;
      let failCount = 0;
      
      for (const record of splitResults.value) {
        try {
          await downloadFile(record);
          successCount++;
          // 添加延迟避免浏览器阻止多个下载
          await new Promise(resolve => setTimeout(resolve, 500));
        } catch (error) {
          failCount++;
          console.error(`下载文件 ${record.fileName} 失败:`, error);
        }
      }
      
      if (successCount > 0) {
        message.success(`批量下载完成！成功：${successCount}个，失败：${failCount}个`);
      } else {
        message.error('批量下载失败');
      }
    } catch (error) {
      console.error('批量下载失败:', error);
      message.error('批量下载失败');
    } finally {
      downloadingAll.value = false;
    }
  };
  
  // 刷新结果
  const refreshResults = () => {
    // 重新执行分表逻辑
    if (canSplit.value) {
      handleSplit();
    } else {
      message.warning('请先完成分表配置');
    }
  };
  
  // 模板上传前处理
  const beforeTemplateUpload = (file: File) => {
    const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                    file.type === 'application/vnd.ms-excel';
    
    if (!isExcel) {
      message.error('只能上传Excel文件作为模板！');
      return false;
    }
    
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isLt5M) {
      message.error('模板文件大小不能超过5MB！');
      return false;
    }
    
    return false; // 阻止自动上传
  };
  
  // 模板上传变化处理
  const handleTemplateUploadChange = (info: any) => {
    if (info.fileList.length > 0) {
      // 解析模板文件
      parseTemplateFile(info.fileList[0].originFileObj);
    }
  };
  
  // 移除模板文件处理
  const handleTemplateRemove = (_file: UploadFile) => {
    // 清空模板数据
    templateInfo.value = null;
    templatePreviewData.value = [];
    templatePreviewColumns.value = [];
    return true;
  };
  
  // 定义预期的模板工作表格式
  const EXPECTED_TEMPLATE_SHEETS = [
    { 
      name: '金融资产', 
      headerRow: 3, 
      dataStartRow: 4
    },
    { 
      name: '物业资产', 
      headerRow: 1, 
      dataStartRow: 2,
      skip: true // 原封不动复制
    },
    { 
      name: '调解场景', 
      headerRow: 1, 
      dataStartRow: 2,
      skip: true // 原封不动复制
    },
    { 
      name: '诉讼场景', 
      headerRow: 1, 
      dataStartRow: 2,
      skip: true // 原封不动复制
    },
    { 
      name: '客户', 
      headerRow: 3, 
      dataStartRow: 4
    },
    { 
      name: '联系人', 
      headerRow: 1, 
      dataStartRow: 2,
      skip: true // 原封不动复制
    },
    { 
      name: '担保人', 
      headerRow: 1, 
      dataStartRow: 2,
      skip: true // 原封不动复制
    },
    { 
      name: '分案关系', 
      headerRow: 1, 
      dataStartRow: 2,
      skip: true // 原封不动复制，但会填充数据
    }
  ];
  
  // 解析模板文件
  const parseTemplateFile = async (file: File) => {
    templatePreviewLoading.value = true;
    try {
      // 创建文件读取器
      const reader = new FileReader();
  
      // 读取文件内容
      const buffer = await new Promise<ArrayBuffer>((resolve, reject) => {
        reader.onload = (e) => {
          if (e.target?.result instanceof ArrayBuffer) {
            resolve(e.target.result);
          } else {
            reject(new Error('无法读取模板文件内容'));
          }
        };
        reader.onerror = reject;
        reader.readAsArrayBuffer(file);
      });
  
      // 使用exceljs处理文件
      const workbook = new ExcelJS.Workbook();
      await workbook.xlsx.load(buffer, {
        ignoreNodes: ['sharedStrings']
      });
  
      // 处理每个工作表
      const processedWorksheets: TemplateWorksheet[] = [];
      let totalDataCount = 0;
  
      workbook.worksheets.forEach((worksheet, index) => {
        const expectedSheet = EXPECTED_TEMPLATE_SHEETS[index];
        
        // 如果工作表被标记为跳过，仍然需要处理以保存原始工作表引用
        if (expectedSheet?.skip) {
          // 创建基本的工作表对象，保存原始引用
          const worksheetData: TemplateWorksheet = {
            name: worksheet.name,
            headers: [],
            data: [],
            columns: [],
            headerRow: expectedSheet.headerRow || 1,
            dataStartRow: expectedSheet.dataStartRow || 2,
            dataCount: 0,
            originalWorksheet: worksheet // 保存原始工作表引用
          };
          processedWorksheets.push(worksheetData);
          return;
        }
        
        // 解析表头（根据预期格式）
        const headers: string[] = [];
        const headerRowNumber = expectedSheet?.headerRow || 1;
        const dataStartRowNumber = expectedSheet?.dataStartRow || 2;
        const headerRow = worksheet.getRow(headerRowNumber);
        
        if (!headerRow || !headerRow.values || !Array.isArray(headerRow.values)) {
          return; // 跳过无效的工作表
        }
  
        // 解析所有表头
        for (let colNumber = 1; colNumber < (headerRow.values as any[]).length; colNumber++) {
          const cellValue = (headerRow.values as any[])[colNumber];
          const headerName = cellValue?.toString()?.trim() || `列${colNumber}`;
          headers[colNumber - 1] = headerName;
        }
  
        // 解析数据行（最多显示前10行作为预览）
        const data: ExcelRow[] = [];
        let rowCount = 0;
        
        worksheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {
          // 跳过表头行之前的所有行
          if (rowNumber < dataStartRowNumber) return;
          
          // 只解析前10行数据用于预览
          if (rowCount >= 10) return;
          
          const rowData: ExcelRow = { key: `row_${rowNumber}` };
          let hasData = false;
          
          for (let colNumber = 1; colNumber <= headers.length; colNumber++) {
            const cell = row.getCell(colNumber);
            let cellValue = null;
            
            try {
              if (cell.value !== null && cell.value !== undefined) {
                cellValue = cell.value;
              } else if (cell.result !== null && cell.result !== undefined) {
                cellValue = cell.result;
              } else if (cell.text) {
                cellValue = cell.text;
              }
            } catch (error) {
              console.warn(`获取模板单元格 ${colNumber} 的值失败:`, error);
              cellValue = null;
            }
            
            const colKey = `col${colNumber}`;
            rowData[colKey] = formatCellValue(cellValue);
            
            if (cellValue !== null && cellValue !== undefined && cellValue !== '') {
              hasData = true;
            }
          }
          
          if (hasData) {
            data.push(rowData);
            rowCount++;
          }
        });
  
        // 生成表格列配置
        const columns: TableColumnsType<any> = [];
        
        headers.forEach((header, colIndex) => {
          const colNumber = colIndex + 1;
          const colKey = `col${colNumber}`;
          columns.push({
            title: header,
            dataIndex: colKey,
            key: colKey,
            width: 120,
            ellipsis: true,
            align: 'center',
            customCell: (record: any) => {
              return {
                innerHTML: formatCellValue(record[colKey])
              };
            }
          });
        });
  
        // 创建工作表对象
        const worksheetData: TemplateWorksheet = {
          name: worksheet.name,
          headers: headers,
          data: data,
          columns: columns,
          headerRow: headerRowNumber,
          dataStartRow: dataStartRowNumber,
          dataCount: rowCount,
          originalWorksheet: worksheet // 保存原始工作表引用
        };
  
        processedWorksheets.push(worksheetData);
        totalDataCount += rowCount;
      });
  
      // 更新模板信息
      templateInfo.value = {
        fileName: file.name,
        sheetCount: workbook.worksheets.length,
        worksheets: processedWorksheets
      };
  
      // 更新预览数据（显示第一个工作表的数据）
      if (processedWorksheets.length > 0) {
        templatePreviewData.value = processedWorksheets[0].data;
        templatePreviewColumns.value = processedWorksheets[0].columns;
      }
      
      message.success(`模板文件解析成功！检测到 ${processedWorksheets.length} 个有效工作表，共 ${totalDataCount} 行数据`);
    } catch (error) {
      message.error('模板文件解析失败');
      console.error('模板解析错误:', error);
    } finally {
      templatePreviewLoading.value = false;
    }
  };
  
  // 预览模板
  const previewTemplate = () => {
    if (templateInfo.value) {
      templatePreviewVisible.value = true;
    }
  };
  
  // 清除模板
  const clearTemplate = () => {
    templateFileList.value = [];
    templateInfo.value = null;
    templatePreviewData.value = [];
    templatePreviewColumns.value = [];
    message.info('已清除模板文件');
  };
  
  // 处理模板标签页切换
  const handleTemplateTabChange = (key: string) => {
    if (templateInfo.value?.worksheets) {
      const index = parseInt(key);
      const worksheet = templateInfo.value.worksheets[index];
      if (worksheet) {
        templatePreviewData.value = worksheet.data;
        templatePreviewColumns.value = worksheet.columns;
      }
    }
  };
  </script>
  
  <style scoped>
  .excel-split-container {
    padding: 0;
  }
  
  .page-header {
    margin-bottom: 24px;
  }
  
  .page-header h2 {
    margin: 0 0 8px 0;
    font-size: 24px;
    font-weight: 600;
    color: #262626;
  }
  
  .page-header p {
    margin: 0;
    color: #8c8c8c;
    font-size: 14px;
  }
  
  .content-wrapper {
    display: flex;
    flex-direction: column;
    gap: 24px;
  }
  
  .upload-section,
  .config-section,
  .result-section {
    width: 100%;
  }
  
  .upload-card,
  .config-card,
  .result-card {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    border-radius: 8px;
  }
  
  .upload-area {
    padding: 20px;
  }
  
  .ant-upload-drag {
    border: 2px dashed #d9d9d9;
    border-radius: 8px;
    background: #fafafa;
    transition: all 0.3s;
  }
  
  .ant-upload-drag:hover {
    border-color: #1890ff;
    background: #f0f8ff;
  }
  
  .ant-upload-drag-icon {
    font-size: 48px;
    color: #1890ff;
    margin-bottom: 16px;
  }
  
  .ant-upload-text {
    font-size: 16px;
    color: #262626;
    margin-bottom: 8px;
  }
  
  .ant-upload-hint {
    font-size: 14px;
    color: #8c8c8c;
    margin: 0;
  }
  
  /* 预览区域样式 */
  .preview-section {
    width: 100%;
  }
  
  .preview-card {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    border-radius: 8px;
  }
  
  /* 分表信息样式 */
  .split-info {
    margin-bottom: 20px;
  }
  
  .highlight {
    color: #1890ff;
    font-weight: 600;
  }
  
  .preview-info {
    margin-bottom: 16px;
    padding: 16px;
    background-color: #fafafa;
    border-radius: 6px;
  }
  
  .preview-table {
    margin-top: 16px;
    max-height: 500px;
    overflow: auto;
    border: 1px solid #f0f0f0;
    border-radius: 6px;
  }
  
  /* 全屏预览样式 */
  .full-preview-container {
    max-height: 80vh;
    overflow: hidden;
  }
  
  .full-preview-header {
    margin-bottom: 16px;
    padding: 16px;
    background-color: #fafafa;
    border-radius: 6px;
  }
  
  .full-preview-table {
    max-height: 70vh;
    overflow: auto;
    border: 1px solid #f0f0f0;
    border-radius: 6px;
  }
  
  /* 机构选项卡样式 */
  .institution-tabs-container {
    margin-top: 16px;
  }
  
  .institution-preview-table {
    max-height: 60vh;
    overflow: auto;
    border: 1px solid #f0f0f0;
    border-radius: 6px;
    margin-top: 16px;
  }
  
  .institution-tabs-container .ant-tabs-card > .ant-tabs-nav .ant-tabs-tab {
    background: #f5f5f5;
    border: 1px solid #d9d9d9;
    border-bottom: none;
    border-radius: 6px 6px 0 0;
    margin-right: 4px;
  }
  
  .institution-tabs-container .ant-tabs-card > .ant-tabs-nav .ant-tabs-tab-active {
    background: #fff;
    border-bottom: 1px solid #fff;
    color: #1890ff;
  }
  
  .institution-tabs-container .ant-tabs-card > .ant-tabs-content {
    border: 1px solid #d9d9d9;
    border-top: none;
    border-radius: 0 0 6px 6px;
    padding: 16px;
    background: #fff;
  }
  
  /* 机构预览样式 */
  .institution-preview-container {
    max-height: 80vh;
    overflow: hidden;
  }
  
  .institution-preview-header {
    margin-bottom: 16px;
    padding: 16px;
    background-color: #f0f8ff;
    border-radius: 6px;
    border-left: 4px solid #1890ff;
  }
  
  .institution-preview-table {
    max-height: 60vh;
    overflow: auto;
    border: 1px solid #f0f0f0;
    border-radius: 6px;
  }
  
  /* 表格样式优化 */
  .ant-table-thead > tr > th {
    background-color: #f5f5f5;
    font-weight: 600;
    text-align: center;
  }
  
  .ant-table-tbody > tr > td {
    text-align: center;
    padding: 8px 12px;
  }
  
  .ant-table-tbody > tr:hover > td {
    background-color: #f0f8ff;
  }
  
  /* 滚动条样式优化 */
  .preview-table::-webkit-scrollbar,
  .full-preview-table::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }
  
  .preview-table::-webkit-scrollbar-track,
  .full-preview-table::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
  }
  
  .preview-table::-webkit-scrollbar-thumb,
  .full-preview-table::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
  }
  
  .preview-table::-webkit-scrollbar-thumb:hover,
  .full-preview-table::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
  }
  
  /* 模板上传区域样式 */
  .template-upload-section {
    margin-top: 24px;
  }
  
  /* 银行名称区域样式 */
  .bank-name-section {
    margin-top: 24px;
  }
  
  .template-upload-area {
    padding: 16px;
  }
  
  .template-upload-area .ant-upload-drag {
    border: 2px dashed #52c41a;
    border-radius: 8px;
    background: #f6ffed;
    transition: all 0.3s;
  }
  
  .template-upload-area .ant-upload-drag:hover {
    border-color: #389e0d;
    background: #f0f9e8;
  }
  
  .template-upload-area .ant-upload-drag-icon {
    font-size: 36px;
    color: #52c41a;
    margin-bottom: 12px;
  }
  
  .template-upload-area .ant-upload-text {
    font-size: 14px;
    color: #262626;
    margin-bottom: 6px;
  }
  
  .template-upload-area .ant-upload-hint {
    font-size: 12px;
    color: #8c8c8c;
    margin: 0;
  }
  
  .template-info {
    margin-top: 16px;
  }
  
  .template-actions {
    display: flex;
    justify-content: flex-end;
  }
  
  /* 模板预览样式 */
  .template-preview-container {
    max-height: 80vh;
    overflow: hidden;
  }
  
  .template-preview-header {
    margin-bottom: 16px;
    padding: 16px;
    background-color: #f6ffed;
    border-radius: 6px;
    border-left: 4px solid #52c41a;
  }
  
  .template-preview-table {
    max-height: 60vh;
    overflow: auto;
    border: 1px solid #f0f0f0;
    border-radius: 6px;
  }
  
  /* 模板工作表样式 */
  .template-worksheets {
    margin-top: 16px;
  }
  
  .template-worksheets-tabs {
    margin-top: 16px;
  }
  
  .worksheet-preview {
    padding: 16px 0;
  }
  
  .worksheet-preview-content {
    padding: 16px 0;
  }
  
  .worksheet-info {
    background-color: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 6px;
    padding: 16px;
    margin-bottom: 20px;
    display: flex;
    gap: 24px;
    flex-wrap: wrap;
  }
  
  .info-item {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  
  .info-label {
    color: #666;
    font-size: 14px;
  }
  
  .info-value {
    color: #1a1a1a;
    font-weight: 500;
    font-size: 14px;
  }
  
  .worksheet-preview-table {
    border: 1px solid #f0f0f0;
    border-radius: 8px;
    overflow: hidden;
    margin-top: 16px;
  }
  
  /* 响应式设计 */
  @media (max-width: 768px) {
    .content-wrapper {
      gap: 16px;
    }
    
    .page-header h2 {
      font-size: 20px;
    }
    
    .upload-area {
      padding: 16px;
    }
    
    .template-upload-area {
      padding: 12px;
    }
    
    .preview-info .ant-descriptions-item-label,
    .full-preview-header .ant-descriptions-item-label,
    .template-preview-header .ant-descriptions-item-label {
      font-size: 12px;
    }
    
    .preview-info .ant-descriptions-item-content,
    .full-preview-header .ant-descriptions-item-content,
    .template-preview-header .ant-descriptions-item-content {
      font-size: 12px;
    }
  }
  </style>
  